package club.kynb.mall.application.flow.pay;

import club.kynb.mall.application.context.OrderPayContext;
import club.kynb.mall.application.model.model.command.OrderPayCommand;
import club.kynb.mall.order.api.IOrderService;
import club.kynb.mall.order.constant.OrderPayStatusEnum;
import club.kynb.mall.order.constant.OrderStatusEnum;
import club.kynb.mall.order.model.dto.OrderDTO;
import club.kynb.mall.payment.constant.TradeOrderStatusEnum;
import club.kynb.mall.payment.dto.ext.PayResultDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author kynb_club@163.com
 * @date: 2021/7/8
 */
@Slf4j
@Component
@AllArgsConstructor
public class PayCompleteNotifyOrderFilter implements Filter<OrderPayContext> {

    private final IOrderService orderService;

    @Override
    public void doFilter(OrderPayContext orderPayContext, FilterInvoker<OrderPayContext> filterInvoker) {
        log.info("支付调用完成通知订单过滤器 start");
        PayResultDTO resultDTO = orderPayContext.getPayResultDTO();
        OrderPayStatusEnum statusEnum = null;
        if(TradeOrderStatusEnum.SUCCESS.equals(resultDTO.getStatus())){
            statusEnum = OrderPayStatusEnum.PAID;
        }else if(TradeOrderStatusEnum.WAITING_4_UPDATE.equals(resultDTO.getStatus())){
            statusEnum = OrderPayStatusEnum.PAYING;
        }
        if(statusEnum != null){
            switch (orderPayContext.getPayRequestDTO().getOrderType()){
                case NORMAL:
                    notifyOrder(orderPayContext,statusEnum);
                    break;
                default:break;
            }
        }

        log.info("支付调用完成通知订单过滤器 end");
        filterInvoker.invoke(orderPayContext);
    }


    private void notifyOrder(OrderPayContext orderPayContext,OrderPayStatusEnum orderPayStatusEnum){
        OrderPayCommand command = orderPayContext.getCommand();
        PayResultDTO payResultDTO = orderPayContext.getPayResultDTO();

        OrderDTO dto = new OrderDTO();
        dto.setInnerOrderNo(command.getInnerOrderNo());
        dto.setOrderStatus(OrderPayStatusEnum.PAID.equals(orderPayStatusEnum) ? OrderStatusEnum.UN_DELIVERY.code() : null);
        dto.setPayNo(payResultDTO.getPayOrderNo());
        dto.setPayChannel(command.getPayChannel());
        dto.setPayStatus(orderPayStatusEnum.getStatus());
        dto.setPayFinishTime(OrderPayStatusEnum.PAID.equals(orderPayStatusEnum) ? new Date() : null);
        dto.setDepositPayTime(new Date());
        dto.setUpdateTime(new Date());
        orderService.updateByOrderNo(dto);
    }

}
